// AJAX 统一成功状态code
var SUCCESS_STATUS_CODE = "0000";

// AJAX 统一IP受限状态code
var IP_FORBIDDEN_STATUS_CODE = "9996";

// AJAX 统一未授权状态code
var NO_AUTH_STATUS_CODE = "9997";

// AJAX 统一未登录状态code
var NO_LOGIN_STATUS_CODE = "9998";

// AJAX 统一失败状态code
var FAIL_STATUS_CODE = "9999";

//测试环境打标志
var _temp_debug_flag = getQueryString('debug');
if (_temp_debug_flag) {
    setStorage('debug', _temp_debug_flag);
}
_temp_debug_flag = getStorage('debug');
if (_temp_debug_flag == 1 || _temp_debug_flag == 'true' || (typeof _temp_debug_flag === 'boolean' && _temp_debug_flag)) {
    debugConsole();
}

layer.iconMsg = function (msg, icon, options) {
    options = options || {};
    layer.msg(msg, $.extend(options, {
        icon: icon,
        tipsMore: true
    }));
};

layer.loading = function (type) {
    type = type || 1;
    layer.load(type, {
        shade: [0.5, '#fff']
    });
};

layer.warn = function (msg, options) {
    layer.iconMsg(msg, 0, options || {});
};

layer.success = function (msg, options) {
    layer.iconMsg(msg, 1, options || {});
};

layer.error = function (msg, options) {
    layer.iconMsg(msg, 2, options || {});
};

layer.question = function (msg, options) {
    layer.iconMsg(msg, 3, options || {});
};

layer.lock = function (msg, options) {
    layer.iconMsg(msg, 4, options || {});
};

layer.bad = function (msg, options) {
    layer.iconMsg(msg, 5, options || {});
};

layer.smile = function (msg, options) {
    layer.iconMsg(msg, 6, options || {});
};

layer.dialog = {};
layer.dialog.open = function (url, dialogOptions, ajaxOptions) {
    ajaxOptions = ajaxOptions || {};
    dialogOptions = dialogOptions || {};
    var successFn = function (data) {
        dialogOptions.content = data;
        dialogOptions.type = 1;
        layer.open(dialogOptions);
    };
    if (typeof url === 'string') {
        dialogOptions = jQuery.extend({}, dialogOptions);
        ajaxOptions = jQuery.extend({
            url: url,
            dataType: 'html'
        }, ajaxOptions);
        if (ajaxOptions.success) {
            var fn = ajaxOptions.success;
            ajaxOptions.success = function (data) {
                data = fn(data);
                if (data.success) {
                    successFn(data.content);
                } else {
                    data.error(data.content);
                }
            }
        } else {
            ajaxOptions.success = successFn;
        }
        jQuery.ajax(ajaxOptions);
    } else if (typeof url === 'object') {
        dialogOptions = url;
        dialogOptions = jQuery.extend({}, dialogOptions);
        layer.open(dialogOptions);
    }
};

/**
 * ajax请求
 */
function ajaxRequest(ajaxParams, fnSuccess, fnError, noMsg) {
    if (typeof fnSuccess === 'boolean') {
        noMsg = fnSuccess;
        fnSuccess = false;
    }
    if (typeof fnError === 'boolean') {
        noMsg = fnError;
        fnError = false;
    }
    var success = function (data) {
        if (typeof data === 'string' || SUCCESS_STATUS_CODE === data.statusCode) {
            if (!noMsg && data.message) {
                layer.success(data.message);
            }
            fnSuccess && fnSuccess(data);
        } else if (NO_LOGIN_STATUS_CODE === data.statusCode || IP_FORBIDDEN_STATUS_CODE === data.statusCode || NO_AUTH_STATUS_CODE === data.statusCode) {
            window.location.href = WEB_ROOT;
        } else if (FAIL_STATUS_CODE === data.statusCode) {
            if (!noMsg && data.message) {
                layer.error(data.message);
            }
            fnError && fnError(data);
        } else {
            if (typeof data === 'object') {
                if (!noMsg && data.message) {
                    layer.error(data.message);
                }
                fnError && fnError(data);
            } else {
                if (!noMsg) {
                    layer.error('未知错误');
                }
            }
            fnError && fnError(data);
        }
    };

    // 公共处理error
    var error = function (jqXHR, textStatus, errorThrown) {
        var data = jqXHR.responseJSON;
        if (data) {
            if (NO_LOGIN_STATUS_CODE === data.statusCode) {
                window.location.href = WEB_ROOT;
            }
            if (data.message) {
                if (!noMsg && data.message) {
                    layer.error(data.message);
                }
            } else {
                if (!noMsg) {
                    layer.error('未知错误');
                }
            }
        }
        fnError && fnError(data, jqXHR, textStatus, errorThrown);
    };

    var default_params = {
        type: 'POST',
        cache: false,
        success: success,
        error: error
    };

    ajaxParams = $.extend(default_params, ajaxParams);

    $.ajax(ajaxParams);
}

/**
 * 初始dataTable对象
 *
 * @param settings
 * @param fnQueryParams
 * @returns {jQuery}
 */
function initDataTable(settings, fnQueryParams) {
    var tableId = settings.tableId || 'list_table';

    // datatables默认设置
    var DATATABLES_DEFAULT_SETTING = {
        ajax: {
            type: "POST"
        },
        responsive: true,
        dom: "<'am-g am-datatable-hd'<'am-u-sm-6'f>>" + "<'am-g'<'am-u-sm-12'tr>>" + "<'am-g am-datatable-footer'<'am-u-sm-2'i><'am-u-sm-1'l><'am-u-sm-4'p>>",
        searching: false,
        ordering: false,
        serverSide: true, // ajax支持
        processing: true,// 加载支持
        language: {
            lengthMenu: '_MENU_ ',
            thousands: ','
        },
        oLanguage: {
            sThousands: ','
        },
        lengthMenu: [20, 50, 100]
    };

    // ajax language 扩展
    var ajax = settings.ajax;

    if (typeof ajax === 'string') {
        ajax = {
            url: ajax
        };
    }

    // 内部默认搜索参数函数
    function innerFnQueryParams() {
        return {};
    }

    fnQueryParams = fnQueryParams || settings.data || innerFnQueryParams;

    // 查询参数拼接
    if (fnQueryParams && typeof fnQueryParams === 'function') {
        ajax.data = function (data) {
            var pageParam = {
                'offset': data.start,
                'limit': data.length
            };
            return $.extend(pageParam, fnQueryParams(data));
        };
    }

    ajax = $.extend(DATATABLES_DEFAULT_SETTING.ajax, ajax);

    // language 扩展
    var language = settings.language || {};
    language = $.extend(DATATABLES_DEFAULT_SETTING.language, language);

    // 重设 ajax language
    settings.ajax = ajax;
    settings.language = language;

    // 扩展column
    var columns = settings.columns || [];
    var _columns = [];
    for (var i = 0, l = columns.length; i < l; i++) {
        var c = columns[i];
        if (typeof c === 'string') {
            c = {
                data: c
            };
        } else if (typeof c === 'function') {
            c = {
                data: 'id',
                render: c
            };
        }
        c = $.extend({
            className: 'am-text-center am-text-middle before-content-top-inherit',
            defaultContent: ''
        }, c);
        _columns.push(c);
    }
    settings.columns = _columns;

    settings = $.extend(DATATABLES_DEFAULT_SETTING, settings);

    return $('#' + tableId).DataTable(settings);
}

/**
 * 初始化上传插件
 */
function initUploadify(id, fnSuccess, fnError, fnStart) {
    var settings = {};
    if (typeof id === 'object') {
        settings = id;
        id = settings.id;
    }
    var default_setting = {
        'auto': false,
        'fileSizeLimit': '5MB',// 最大大小
        'fileTypeExts': '*.jpg;*.png;*.jpeg;*.bmp;*.gif', // 控制可上传文件的扩展名，启用本项时需同时声明fileDesc
        'fileTypeDesc': '请选择jpg,png,jpeg,bmp,gif格式',// 与fileTypeExts配套使用，用来设置选择文件对话框中的提示文本
        'width': '100',// 按钮宽度
        'height': '32',// 按钮高度
        'multi': true,
        'progressData': 'percentage',// 设置上传进度显示方式，percentage显示上传百分比，speed显示上传速度
        'removeCompleted': false,// 是否自动将已完成任务从队列中删除，如果设置为false则会一直保留此任务显示。
        'swf': WEB_ROOT + '/assets/js/uploadify/uploadify.swf',// 控件flash文件位置
        'uploader': WEB_ROOT + '/file/upload/' + (settings.type || 0),
        'queueID': 'queue-' + id,// 与下面HTML的div.id对应
        'buttonText': '选择文件',// 上传按钮显示内容，还有个属性可以设置按钮的背景图片
        'method': 'POST',
        'buttonClass': 'am-input-group-btn',
        'fileObjName': 'file-' + id,
        'onUploadSuccess': function (file, data, response) {// 上传成功之后把文件名存在隐藏域
            fnSuccess && fnSuccess(file, data, response);
        },
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            fnError && fnError(file, errorCode, errorMsg, errorString);
        },
        'onUploadStart': function (file) {// 开始上传时触发
            fnStart && fnStart(file);
        },
        'onFallback': function () {// 当Uploadify初始化过程中检测到当前浏览器不支持flash时触发。
            alert("当前浏览器不支持FLASH，请更换浏览器再试！");
        },
        'onSelectError': function () {
            alert("选择文件失败！");
        }

    };
    settings = $.extend(default_setting, settings);
    $('#' + id).uploadify(settings);
}

// 初始化富文本编辑器
function initEditor(offset) {
    $('*[editor]').each(function (index) {
        $(this).attr('id', "user-editor-" + (index + (offset || 0)));
        UE.getEditor($(this).attr('id'), {
            initialFrameHeight: 400
        });
    });
}

/**
 * 获取url查询参数
 * @param name
 * @returns {*}
 */
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var matchs = window.location.search.substr(1).match(reg);
    if (matchs != null) {
        return decodeURI(decodeURIComponent(matchs[2]));
    }
    return null;
}


/**
 * 校验是否支持H5 storage IOS 的Safari 在无痕迹模式下是不支持的哦
 * @returns {boolean}
 */
function isStorageSupported() {
    var testKey = 'test', storage = window.sessionStorage;
    try {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return true;
    } catch (error) {
        return false;
    }
}

/**
 * 设置临时变量
 * @param key
 * @param value
 */
function setTempStorage(key, value) {
    if (isStorageSupported()) {
        sessionStorage.setItem(key, value);
    } else {
        jQuery.cookie(key, value);
    }
}

/**
 * 设置临时变量
 * @param key
 * @param value
 */
function setStorage(key, value) {
    if (isStorageSupported()) {
        localStorage.setItem(key, value);
    } else {
        jQuery.cookie(key, value);
    }
}

/**
 * 获取临时变量 同时决定是否清除
 * @param key
 * @param isClear
 * @returns {*}
 */
function getTempStorage(key, isClear) {
    var value = null;
    if (isStorageSupported()) {
        value = sessionStorage.getItem(key);
    } else {
        value = jQuery.cookie(key);
    }
    if (isClear) {
        clearTempStorage(key);
    }
    return value;
}

/**
 * 获取临时变量 同时决定是否清除
 * @param key
 * @param isClear
 * @returns {*}
 */
function getStorage(key, isClear) {
    var value = null;
    if (isStorageSupported()) {
        value = localStorage.getItem(key);
    } else {
        value = jQuery.cookie(key);
    }
    if (isClear) {
        clearStorage(key);
    }
    return value;
}

/**
 * 清楚临时变量
 * @param key
 */
function clearTempStorage(key) {
    if (isStorageSupported()) {
        if (key !== undefined) {
            sessionStorage.removeItem(key);
        } else {
            sessionStorage.clear();
        }
    } else {
        jQuery.cookie(key, '');
    }
}

/**
 * 清楚临时变量
 * @param key
 */
function clearStorage(key) {
    if (isStorageSupported()) {
        if (key !== undefined) {
            localStorage.removeItem(key);
        } else {
            localStorage.clear();
        }
    } else {
        jQuery.cookie(key, '');
    }
}

/**
 * 创建debug
 */
function debugConsole() {
    var vConsoleScript = document.createElement('script');
    vConsoleScript.src = WEB_ROOT + '/assets/js/vconsole.min.js';
    jQuery(document.scripts[0]).after(vConsoleScript);
}